<template>
	<div>
		<div class="container">
			<el-table
				border
				class="table"
				id="my-table"
				v-loading="loading"
				ref="multipleTableRef"
				:header-cell-style="{ backgroundColor: 'var(--backcor)' }"
				:cell-style="{ height: '50px', backgroundColor: 'var(--backcor)' }"
				:data="userList"
				style="width: 100%"
				height="90%"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" />
				<el-table-column property="id" label="用户id" width="200">
				</el-table-column>
				<el-table-column property="name" label="用户名" width="200" />
				<el-table-column
					property="organization"
					label="所属组织"
					min-width="100"
					show-overflow-tooltip
				/>
				<el-table-column
					property="phone"
					label="电话"
					min-width="90"
					show-overflow-tooltip
				/>
				<el-table-column
					property="createdAt"
					label="注册时间"
					min-width="120"
					show-overflow-tooltip
				>
					<template #default="scope">
						<div style="display: flex; align-items: center">
							<el-icon>
								<timer />
							</el-icon>
							<span style="margin-left: 10px">{{
								time(new Date(scope.row.createdAt))
							}}</span>
						</div>
					</template>
				</el-table-column>

				<el-table-column
					property="operation"
					label="operation"
					fixed="right"
					width="200"
				>
					<template #default="scope">
						<div class="button">
							<el-button
								link
								type="primary"
								@click.prevent="deleteRow([userList[scope.$index].id])"
								size="small"
								>删除用户
							</el-button>
							<el-button
								link
								type="primary"
								@click.prevent="reset(scope.$index)"
								size="small"
								>重置密码
							</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<div class="buttons">
				<div class="left">
					<el-button
						:plain="multipleSelection.length == 0"
						@click="deletes"
						:disabled="multipleSelection.length == 0"
						type="danger"
						>批量删除</el-button
					>
					<el-button
						type="primary"
						:disabled="multipleSelection.length == 0"
						@click="(dialogVisible = true), (titles = '更换用户权限')"
						>更换用户权限</el-button
					>
					<el-button type="primary" @click="dialogVisible3 = true"
						>添加用户</el-button
					>
					<el-button type="primary" @click="dialogVisible2 = true"
						>添加敏感词</el-button
					>
					<el-button type="primary" @click="exportExcelHandle('my-table')"
						>导出表格</el-button
					>
					<el-button
						type="primary"
						@click="(dialogVisible = true), (titles = '导出组织用户信息')"
						>导出组织用户信息</el-button
					>
					<el-form :model="form" label-width="120px">
						<el-form-item label="姓名">
							<el-input v-model="form.name" />
						</el-form-item>
					</el-form>
					<el-button
						type="primary"
						@click="requestUser(0)"
						:icon="Search"
						color="#409EFF"
						>搜索</el-button
					>
					<el-button @click="(form.name = ''), requestUser(0)" plain>重置</el-button>
				</div>
				<el-pagination
					class="pagination"
					background
					layout="prev, pager, next"
					@current-change="currentChange"
					:total="pageCount * 10"
				/>
			</div>
		</div>
		<!-- 添加用户 -->
		<teleport to="body">
			<el-dialog v-model="dialogVisible3" title="添加用户" width="30%">
				<el-upload
					ref="upload"
					class="upload-demo"
					:action="HTTP + '/user/excelImport'"
					method="PUT"
					:headers="{ Authorization: store.user.token }"
					:limit="1"
					:on-change="handleAvatarChangeUser"
					:before-upload="beforeAvatarUploadUser"
					name="file"
					:on-success="handleAvatarSuccessUser"
					:on-exceed="handleExceed"
					:auto-upload="false"
				>
					<template #trigger>
						<el-button type="primary">选择文件</el-button>
					</template>
					<el-button
						style="margin-left: 20px"
						class="ml-3"
						type="success"
						@click="submitUpload"
					>
						开始上传
					</el-button>
					<template #tip>
						<div class="el-upload__tip text-red">限制1个文件，新文件将覆盖旧文件</div>
					</template>
				</el-upload>
			</el-dialog>
		</teleport>
		<!-- 添加敏感词 -->
		<teleport to="body">
			<el-dialog v-model="dialogVisible2" title="添加敏感词" width="30%">
				<el-upload
					ref="upload2"
					class="upload-demo"
					:action="HTTP + '/sensitive_vocabulary/txtImport'"
					method="PUT"
					:headers="{ Authorization: store.user.token }"
					:limit="1"
					:on-change="handleAvatarChangeUser2"
					:before-upload="beforeAvatarUploadUser2"
					name="file"
					:on-success="handleAvatarSuccessUser2"
					:on-exceed="handleExceed2"
					:auto-upload="false"
				>
					<template #trigger>
						<el-button type="primary">选择文件</el-button>
					</template>
					<el-button
						style="margin-left: 20px"
						class="ml-3"
						type="success"
						@click="submitUpload2"
					>
						开始上传
					</el-button>
					<template #tip>
						<div class="el-upload__tip text-red">限制1个文件，新文件将覆盖旧文件</div>
					</template>
				</el-upload>
			</el-dialog>
		</teleport>
		<!-- 更新用户权限 -->
		<teleport to="body">
			<el-dialog v-model="dialogVisible" :title="titles" width="30%">
				<el-select
					v-model="input"
					class="m-2"
					placeholder="选择组织"
					style="margin-left: 5px; width: 70%"
				>
					<el-option
						v-for="item in options"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					/>
				</el-select>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="dialogVisible = false">取消</el-button>
						<el-button type="primary" @click="update()"> 确认 </el-button>
					</span>
				</template>
			</el-dialog>
		</teleport>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import {
	showAllUser,
	resetPassword,
	deleteUser,
	updateRole,
	listOrganization,
	excelExport,
} from "@/request/api";
import type { List } from "@/type/admin";
import { ElTable } from "element-plus";
import {
	ElMessage,
	ElMessageBox,
	ElNotification,
	genFileId,
} from "element-plus";
import type { UploadProps, UploadInstance, UploadRawFile } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { useStore } from "@/stores/counter";
import { time } from "@/hooks/index";
// 导入封装方法
import excelExportUtil from "@/hooks/excelExportUtil.js";

// 导出
const exportExcelHandle = (tableId: string) => {
	excelExportUtil.exportExcel(tableId, "文件名", ".xls", true);
};
//导出全部用户
const getExcelExport = () => {
	if (input.value == "") return ElMessage.error("请选择组织id");
	excelExport(input.value).then((res: any) => {
		const blob = new Blob([res.data], {
			type: "application/octet-stream; charset=utf-8",
		});

		const a = document.createElement("a"); //创建一个a标签
		a.download = res.fileName; //指定文件名称
		a.style.display = "none"; //页面隐藏
		a.href = URL.createObjectURL(blob); // href用于下载地址
		document.body.appendChild(a); //插到页面上
		a.click(); //通过点击触发
		URL.revokeObjectURL(a.href); //释放URL 对象
		document.body.removeChild(a); //删掉a标签
	});
};
const store = useStore();
let HTTP = import.meta.env.VITE_HTTP;
interface Request {
	/**
	 * 关键词，可按照id，姓名模糊匹配
	 */
	keyword?: string;
	/**
	 * 页码
	 */
	pageIndex?: number;
	/**
	 * 页大小
	 */
	pageSize?: number;
}

let options = reactive<{ id: number; name: string }[]>([]);
let pageIndex = 0;
let loading = ref(false);
let userList = reactive<List[]>([]); //用户列表
let pageCount = ref<number>(0); //总页数
let dialogVisible2 = ref(false);
//添加敏感词
const upload2 = ref<UploadInstance>();
const submitUpload2 = () => {
	upload2.value!.submit();
};

const handleExceed2: UploadProps["onExceed"] = (files) => {
	upload2.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload2.value!.handleStart(file);
};
//文件格式验证
const beforeAvatarUploadUser2: UploadProps["beforeUpload"] = (rawFile) => {
	if (rawFile.type != "text/plain") {
		ElMessage.error("请上传text文件");
		return false;
	} else if (rawFile.size / 1024 / 1024 > 5) {
		ElMessage.error("Avatar picture size can not exceed 5MB!");
		return false;
	}
	return true;
};
//当选择文件时触发
const handleAvatarChangeUser2: UploadProps["onSuccess"] = (
	response,
	uploadFile
) => {
	if (!beforeAvatarUploadUser2(response.raw)) upload2.value!.clearFiles();
};
//上传成功回调
const handleAvatarSuccessUser2: UploadProps["onSuccess"] = (
	response,
	uploadFile
) => {
	if (response.data) ElMessage.success(response.data);
	else ElMessage.error(response.msg);
	dialogVisible2.value = false;
};

//更新用户权限
let dialogVisible = ref(false);
let titles = ref("更新用户权限");
let input = ref<string>("");
const update = () => {
	if (titles.value == "导出组织用户信息") {
		return getExcelExport();
	}
	if (input.value == "") return ElMessage.error("请输入组织id");
	let arr: string[] = [];
	multipleSelection.value.forEach((e) => {
		arr.push(e.id);
	});
	updateRole<{
		userIds: string[];
		organizationId: string;
	}>({
		userIds: arr,
		organizationId: input.value,
	})
		.then((res) => {
			return res.data ? Promise.resolve(res.data) : Promise.reject(res.msg);
		})
		.then((res: string) => {
			ElMessage({
				message: res,
				type: "success",
			});
			dialogVisible.value = false;
			requestUser(pageIndex);
		})
		.catch((err) => {
			ElMessage.error(err);
		});
};

//表格处理逻辑
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<List[]>([]); //选中的表格
const handleSelectionChange = (val: List[]) => {
	multipleSelection.value = val;
};
//分页
const currentChange = (e: number) => {
	pageIndex = e;
	requestUser(pageIndex);
};

/**重置用户密码 */
const reset = (index: number) => {
	ElMessageBox.confirm("确定要重置该用户密码吗?", "Warning", {
		confirmButtonText: "OK",
		cancelButtonText: "取消",
		type: "warning",
	})
		.then(() => {
			return Promise.resolve("1");
		})
		.then((res) => {
			return resetPassword(userList[index].id);
		})
		.then((res) => {
			ElMessage({
				message: "重置成功",
				type: "success",
			});
		});
};

//单个删除用户
const deleteRow = (arr: string[]) => {
	ElMessageBox.confirm("确定要删除吗?", "Warning", {
		confirmButtonText: "OK",
		cancelButtonText: "取消",
		type: "warning",
	})
		.then(() => {
			return deleteUser(arr);
		})
		.then((res) => {
			ElMessage({
				message: "删除成功",
				type: "success",
			});
			requestUser(0);
		});
};
/**
 * 批量删除
 */
const deletes = () => {
	let arr: string[] = [];
	multipleSelection.value.forEach((e) => {
		arr.push(e.id);
	});
	deleteRow(arr);
};
//搜索
const form = reactive({
	name: "",
});

/**
 * 获取数据
 * @param pageIndex 页码
 */
const requestUser = (pageIndex: number) => {
	loading.value = true;
	showAllUser<Request>({
		pageIndex,
		keyword: form.name,
		pageSize: 15,
	}).then((res) => {
		userList.length = 0;
		pageIndex++;
		pageCount.value = res.data.pageCount;
		userList.push(...res.data.list);
		nextTick(() => {
			loading.value = false;
		});
	});
	//获取组织
	listOrganization().then((res) => {
		options.length = 0;
		options.push(...res.data);
	});
};
requestUser(pageIndex);

//上传用户
let dialogVisible3 = ref(false);
const upload = ref<UploadInstance>();

const handleExceed: UploadProps["onExceed"] = (files) => {
	upload.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload.value!.handleStart(file);
};
//文件格式验证
const beforeAvatarUploadUser: UploadProps["beforeUpload"] = (rawFile) => {
	if (
		rawFile.type !=
		"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	) {
		ElMessage.error("请上传xls、xlsx文件");
		return false;
	} else if (rawFile.size / 1024 / 1024 > 5) {
		ElMessage.error("Avatar picture size can not exceed 5MB!");
		return false;
	}
	return true;
};
//当选择文件时触发
const handleAvatarChangeUser: UploadProps["onSuccess"] = (
	response,
	uploadFile
) => {
	if (!beforeAvatarUploadUser(response.raw)) upload.value!.clearFiles();
};
//上传成功回调
const handleAvatarSuccessUser: UploadProps["onSuccess"] = (
	response,
	uploadFile
) => {
	if (response.data) ElMessage.success(response.data);
	else ElMessage.error(response.msg);
	dialogVisible3.value = false;
	pageIndex = 0;
	requestUser(pageIndex);
};

const submitUpload = () => {
	upload.value!.submit();
};
</script>

<style lang="less" scoped>
.button {
	width: 100%;
	.flexSa();
}

.table {
	background-color: @backColor;
	color: @color;
}

:deep(.el-form-item) {
	margin-bottom: 0px;
	margin-right: 5px;
}

:deep(.el-table__inner-wrapper) {
	height: 100% !important;
}

center:deep(.el-icon) {
	color: #000 !important;
}

.container {
	width: 95%;
	overflow: hidden;
	display: flex;
	flex-wrap: wrap;
	height: 95%;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);

	.buttons {
		width: 100%;
		.flexAc();

		justify-content: space-between;
	}

	.left {
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}
}
</style>
